setTimeout(() => {
    console.log(window)
}, 3000)
new Vue({
    el: '#app',
    data: function() {
        return {
            number: '',
            pwd: '',
            visible: false,
            form: {
                number: '',
                pwd: ''
            },
            labelPosition: 'left',
            isPuppet: true,
            controlId: '',         // 控制方id
            controllerSignal: ''   // 控制方signal
        }
    },
    mounted() {
        this.number = this.randomString({len: 6, isNumber: true})
        this.pwd = this.randomString()
        window.socket = io.connect("http://localhost:3000");
        // client-side
        socket.on("connect", () => {
            console.log(socket.id); // x8WIv7-mJelg7on_ALbx
            socket.emit('createRoom', JSON.stringify({
                roomId: socket.id, 
                number: this.number,
                pwd: this.pwd
            }))
        });

        socket.on('answer', (data) => {
            console.log('get socket answer')
            console.log('answer data:', data)
            if (!this.isPuppet) peer.signal(JSON.parse(data))
        })

        socket.on('puppet', (data) => {
            this.controllerSignal = data.offer
            this.controlId = data.controlId
            this.initPeer(false)
        })

        socket.on('authed', data => {
            console.log('get socket authed')
            console.log('authed data:', data)
        })

        socket.on('puppet-signal', data => {
            console.log('收到傀儡signal')
            // peer.signal(data)
        })
    },
    methods: {
        // 改变角色为控制方
        changeRole () {
            this.isPuppet = false
            this.initPeer(true)
        },
        randomString(obj = {}) {  
            if (!obj.len) obj.len = 12
            const numString = "0123456789"
            const allStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
            const charLength = obj.isNumber ? numString.length : allStr.length
            let str = "";
            for (i = 0; i < obj.len; i++) {
                if (obj.isNumber) {
                    str += numString.charAt(Math.floor(Math.random() * charLength))
                } else {
                    str += allStr.charAt(Math.floor(Math.random() * charLength))
                }
            };
            return str
        },
        connect () {
            console.log('click connect')
            if (!this.form.number.trim() || !this.form.pwd.trim()) {
                alert('信息填写不完整')
                return
            }
            // 发送傀儡的序列号和密码，拿到傀儡的signal
            socket.emit('control', JSON.stringify({
                number: this.form.number, 
                pwd: this.form.pwd,
                signal: this.controllerSignal
             }))
        },
        initPeer (initiator) {
            window.peer = new SimplePeer({
                initiator,
                trickle: false
            })

            if (!initiator) {
                // setTimeout(() => {
                //     socket.emit('push-puppet-signal', JSON.stringify(data))
                // }, 2000) 
                peer.signal(JSON.parse(this.controllerSignal))
            }

            peer.on('error', err => console.log('error', err))

            peer.on('signal', data => {
                console.log('SIGNAL', JSON.stringify(data))
                document.querySelector('#outgoing').textContent = JSON.stringify(data)
                if (initiator) {
                    this.controllerSignal = JSON.stringify(data)
                } else {
                    socket.emit('push-puppet-answer', {
                        controlId: this.controlId,
                        answer: JSON.stringify(data)
                    })
                }
            })

            document.querySelector('form').addEventListener('submit', ev => {
                ev.preventDefault()
                peer.signal(JSON.parse(document.querySelector('#incoming').value))
            })

            peer.on('connect', () => {
                console.log('连接成功')
                setInterval(() => {
                    peer.send(`${this.isPuppet ? '傀儡' : '控制方'}发送：${Date.now()}`)
                }, 1000);
            })

            peer.on('data', data => {
                console.log('data: ' + data)
            })
            
        }
    },
})